// pages/post_detail/post_detail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    post: {},
    comment_content: "",
    comments: [],
    keyboardHeight: 0, // 键盘高度
  },


  // 生命周期函数--监听页面加载
  onLoad(options) {
    const postId = options.id; // 获取传递过来的帖子 ID
    this.getPostInfo(postId);
    this.getPostComments(postId);
  },

  // 获取帖子的详细信息
  getPostInfo: function (postId) {
    wx.request({
      url: `${app.globalData.baseUrl}/api/user/community/post/${postId}`,
      method: "GET",
      success: (res) => {
        this.setData({
          post: res.data.data
        });
      },
      fail: (err) => {
        console.log(err)
      },
    })
  },
  // 获取帖子对应的评论信息
  getPostComments: function (postId) {
    wx.request({
      url: `${app.globalData.baseUrl}/api/user/community/comment`,
      method: "GET",
      data: {
        postId : postId
      },
      success: (res) => {
        console.log(res.data.data)
        this.setData({
          comments: res.data.data
        });
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },

  // 发布评论
  submitComment: function() {
    const postId = this.data.post.id; // 直接从 data 中获取 post.id
    const userId = wx.getStorageSync('userId')
    const comment = {
      postId: postId,
      userId: userId,
      content: this.data.comment_content,
    }
    wx.request({
      url: `${app.globalData.baseUrl}/api/user/community/comment`,
      method: "POST",
      header: {
        'Content-Type': 'application/json' // 设置请求头，告知服务器请求体格式是JSON
      },
      data: comment,
      success: (res) => {
        console.log(res.data.data)
         // 清空输入框内容
        this.setData({
          comment_content: ""
        });
        // 在这里重新获取最新的评论列表
        this.getPostComments(postId);

      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
 
  bindCommentInput(e) {
    this.setData({ comment_content: e.detail.value });
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.onKeyboardHeightChange(res => {
      this.setData({
        keyboardHeight: res.height
      })
    })
  },


})